package com.zahb.qadx.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luozm.captcha.Captcha;
import com.zahb.qadx.BuildConfig;
import com.zahb.qadx.MainActivity;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.CommonResponse;
import com.zahb.qadx.model.DataLogin;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.adapter.TrainTaskAdapter;
import com.zahb.qadx.ui.view.captcha.CaptchaDialog;
import com.zahb.qadx.util.ActivityManager;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.EditTextHelper;
import com.zahb.qadx.util.InputMethodUtil;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.MD5Util;
import com.zahb.qadx.util.RegularUtil;
import com.zahb.qadx.util.SimpleTextWatcher;
import com.zahb.qadx.util.SmsCodeViewWrapper;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
//登录页面
public class LoginActivity extends BaseActivity {

    @BindView(R.id.tv_login_type)
    AppCompatTextView tvLoginType;
    @BindView(R.id.et_account)
    AppCompatEditText etAccount;
    @BindView(R.id.et_pwd)
    AppCompatEditText etPwd;
    @BindView(R.id.layout_sms_code_view)
    RelativeLayout layoutSmsCodeView;
    @BindView(R.id.btn_login)
    AppCompatButton btnLogin;
    @BindView(R.id.tv_find_pwd)
    AppCompatTextView tvFindPwd;
    @BindView(R.id.tv_login_type_change)
    AppCompatTextView tvLoginTypeChange;

    @BindView(R.id.login_check)
    CheckBox checkBox;
    @BindView(R.id.tv_userAgreement)
    TextView userAgreement;
    @BindView(R.id.tv_privacyAgreement)
    TextView privacyAgreement;
    private SmsCodeViewWrapper mSmsCodeViewWrapper;

    @SuppressLint("StaticFieldLeak")
    public static LoginActivity sLoginActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        sLoginActivity = this;
        mAddActivityToCache = false;
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().removeActivity(ActivityManager.KEY_ALL_ACTIVITY, this);
        LiveEventBus.get(Constant.KEY_RESET_PWD, String.class)
                .observe(this, s -> etPwd.setText(s));

        if (getIntent().getBooleanExtra("isUserLauncher", false)) {
            etAccount.setText(getIntent().getStringExtra("account"));
            etPwd.setText(getIntent().getStringExtra("pwd"));
        } else {
            if (!isTaskRoot()) {// 不在栈底，结束界面
                finish();
            } else {// 在栈底，即为首次启动
                SharedPreferences sp = getSharedPreferences("AccountInfo", MODE_PRIVATE);
                String loginDataStr = sp.getString("loginData", "");
                if (!CompatHelper.isEmpty(loginDataStr)) {
                    try {
                        /*// 有登录数据，直接去首页
                        DataLogin dataLogin = JsonUtil.getGson().fromJson(loginDataStr, DataLogin.class);
                        BaseApplication.getContext().setDataLogin(dataLogin);
                        Intent intent = new Intent(getContext(), MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        String[] array = LoginActivity.getAccountInfo(getContext());
        etAccount.setText(array[0]);
        etPwd.setText(array[1]);
    }

    @Override
    protected void onDestroy() {
        sLoginActivity = null;
        super.onDestroy();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mTopBarStartContainer.setVisibility(View.INVISIBLE);
        EditTextHelper.getEditTextDeleteIconWrapper(etAccount).setTextWatcher(mSimpleTextWatcher);
        EditTextHelper.getEditTextDeleteIconWrapper(etPwd).setTextWatcher(mSimpleTextWatcher);
        if (TextUtils.equals(BuildConfig.BUILD_TYPE, "debug")) {
//            etAccount.setText(new StringBuilder("17310019920"));
//            etPwd.setText(new StringBuilder("019920"));
            //            etAccount.setText(new StringBuilder("18210220536"));
//            etPwd.setText(new StringBuilder("220536"));

            //            etAccount.setText(new StringBuilder("13800000000"));
//            etPwd.setText(new StringBuilder("000000"));
        }
        mSmsCodeViewWrapper = new SmsCodeViewWrapper(layoutSmsCodeView);
        mSmsCodeViewWrapper.setOnGetSmsCodeViewClickListener(view -> {
            InputMethodUtil.hideInputMethod(getActivity());
            getSmsCodeCheck();
            //getSmsCode();
        });
        mSmsCodeViewWrapper.setTextWatcher(mSimpleTextWatcher);
        initViewFindPwd();
        //initViewPrivacyAgreement();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.login;
    }

    @OnClick({R.id.btn_login, R.id.tv_login_type_change,R.id.tv_userAgreement, R.id.tv_privacyAgreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                InputMethodUtil.hideInputMethod(getActivity());
                if (getString(R.string.login_type_account).equals(CompatHelper.getString(tvLoginType))) {
                    loginAccount();
                } else if (getString(R.string.login_type_sms_code).equals(CompatHelper.getString(tvLoginType))) {
                    loginSmsCode();
                }
                break;
            case R.id.tv_login_type_change:// 切换登录方式
                InputMethodUtil.hideInputMethod(getActivity());
                if (getString(R.string.login_type_account).equals(CompatHelper.getString(tvLoginType))) {
                    tvLoginType.setText(R.string.login_type_sms_code);
                    tvLoginTypeChange.setText(R.string.login_type_account);
                    etAccount.setHint(R.string.login_hint_account_phone);
                    etPwd.setVisibility(View.GONE);
                    layoutSmsCodeView.setVisibility(View.VISIBLE);
                } else if (getString(R.string.login_type_sms_code).equals(CompatHelper.getString(tvLoginType))) {
                    tvLoginType.setText(R.string.login_type_account);
                    tvLoginTypeChange.setText(R.string.login_type_sms_code);
                    etAccount.setHint(R.string.login_hint_account);
                    etPwd.setVisibility(View.VISIBLE);
                    layoutSmsCodeView.setVisibility(View.GONE);
                }
                checkButton();
                break;
            case R.id.tv_userAgreement://<用户协议>
                String url = WebViewHelper.getBaseUrl() + "userAgreement?fromType=1&version=" + TrainTaskAdapter.getVersionCode(LoginActivity.this);
                Log.e("MyWebViewActivity", "url: " + url);
                MyWebViewActivity.actionStart(LoginActivity.this, url, "", 1);
                break;
            case R.id.tv_privacyAgreement://《隐私政策》
                String url1 = WebViewHelper.getBaseUrl() + "privacyAgreement?fromType=1&version=" + TrainTaskAdapter.getVersionCode(LoginActivity.this);
                Log.e("MyWebViewActivity", "url: " + url1);
                MyWebViewActivity.actionStart(LoginActivity.this, url1, "", 1);
                break;
        }
    }

    public static void actionStart(Context context) {
        actionStart(context, "", "");
    }

    public static void actionStart(Context context, String account, String pwd) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("isUserLauncher", true);
        intent.putExtra("account", account);
        intent.putExtra("pwd", pwd);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    private void saveAccountInfo(@NonNull String account, @NonNull String pwd) {
        SharedPreferences sp = getSharedPreferences("AccountInfo", MODE_PRIVATE);
        sp.edit().putString("account", account).putString("pwd", pwd).apply();
    }

    public static String[] getAccountInfo(Context context) {
        SharedPreferences sp = context.getSharedPreferences("AccountInfo", MODE_PRIVATE);
        String[] array = new String[2];
        array[0] = sp.getString("account", "");
        array[1] = sp.getString("pwd", "");
        return array;
    }

    private SimpleTextWatcher mSimpleTextWatcher = new SimpleTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            checkButton();
        }
    };

    // 设置按钮状态
    private void checkButton() {
        if (getString(R.string.login_type_account).equals(CompatHelper.getString(tvLoginType))) {
            btnLogin.setEnabled(!CompatHelper.isEmpty(etAccount) && !CompatHelper.isEmpty(etPwd));
        } else if (getString(R.string.login_type_sms_code).equals(CompatHelper.getString(tvLoginType))) {
            btnLogin.setEnabled(!CompatHelper.isEmpty(etAccount) && !TextUtils.isEmpty(mSmsCodeViewWrapper.getSmsCode()));
        }
    }

    // 找回密码添加变色和点击事件
    private void initViewFindPwd() {
        String findPwd = CompatHelper.getString(tvFindPwd);
        SpannableStringBuilder builder = new SpannableStringBuilder(findPwd);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_409eff));
        builder.setSpan(colorSpan, findPwd.length() - 2, findPwd.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent intent = new Intent(getContext(), ResetPwdActivity.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.blue_409eff));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        builder.setSpan(clickableSpan, findPwd.length() - 2, findPwd.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvFindPwd.setText(builder);
        tvFindPwd.setMovementMethod(LinkMovementMethod.getInstance());
        tvFindPwd.setHighlightColor(getResources().getColor(android.R.color.transparent));
    }

    //协议的点击事件
    private void initViewPrivacyAgreement() {
        String findPwd = CompatHelper.getString(privacyAgreement);
        SpannableStringBuilder builder = new SpannableStringBuilder(findPwd);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_409eff));
        builder.setSpan(colorSpan, findPwd.length() - 11, findPwd.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                String url = WebViewHelper.getBaseUrl() + "privacyAgreement?fromType=1&version=" + TrainTaskAdapter.getVersionCode(LoginActivity.this);
                Log.e("MyWebViewActivity", "url: " + url);
                MyWebViewActivity.actionStart(LoginActivity.this, url, "", 1);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.blue_409eff));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        builder.setSpan(clickableSpan, findPwd.length() - 11, findPwd.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        privacyAgreement.setText(builder);
        privacyAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        privacyAgreement.setHighlightColor(getResources().getColor(android.R.color.transparent));
    }
    // 账户密码登录
    private void loginAccount() {
        String account = CompatHelper.getString(etAccount);
        String pwd = CompatHelper.getString(etPwd);
        if (!RegularUtil.isValidMobileNumber(account) && !RegularUtil.isValidCid(account)) {
            showBindToast("请输入手机号或者身份证号");
            return;
        }
        /*if (!RegularUtil.isValidPassword(pwd)) {
            showBindToast("密码格式错误");
            return;
        }*/
        if (!checkBox.isChecked()){
            showBindToast("请勾选下方《用户协议》与《隐私政策》即为同意登录");
            return;
        }
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .loginTypeAccount(account, MD5Util.stringToMD5(pwd))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    loginRequestSuccess(response);
                    if (response.getStatusCode() == 200) {
                        saveAccountInfo(account, pwd);
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    Tips.RequestError(getActivity());
                }));
    }

    // 手机验证登录
    private void loginSmsCode() {
        String phone = CompatHelper.getString(etAccount);
        String smsCode = mSmsCodeViewWrapper.getSmsCode();
        if (!RegularUtil.isValidMobileNumber(phone)) {
            showBindToast("手机号格式错误");
            return;
        }
        if (!RegularUtil.isValidSmsCode(smsCode)) {
            showBindToast("验证码错误或已过期");
            return;
        }
        if (!checkBox.isChecked()){
            showBindToast("请勾选下方《用户协议》与《隐私政策》即为同意登录");
            return;
        }
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .loginTypeSmsCode(phone, smsCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    loginRequestSuccess(response);
                    if (response.getStatusCode() == 200) {
                        saveAccountInfo(phone, "");
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    Tips.RequestError(getActivity());
                }));
    }

    // 登录请求成功
    private void loginRequestSuccess(CommonResponse<DataLogin> response) {
        if (response.getStatusCode() == 200) {
            showBindToast("登录成功");
            BaseApplication.getContext().setDataLogin(response.getData());
            SharedPreferences sp = getSharedPreferences("AccountInfo", MODE_PRIVATE);
            sp.edit().putString("loginData", JsonUtil.getGson().toJson(response.getData())).apply();
            LiveEventBus.get(Constant.KEY_USER_LOGIN_STATUS_CHANGED, DataLogin.class).post(response.getData());
            Intent intent = new Intent(getContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();
        } else {
            showBindToast(response.getErrorInfo());
        }
    }

    private void showCaptchaDialog() {
        CaptchaDialog.showCaptchaDialog(getContext(), new Captcha.CaptchaListener() {
            @Override
            public String onAccess(long time) {
                getSmsCode();
                return null;
            }

            @Override
            public String onFailed(int failCount) {
                return null;
            }

            @Override
            public String onMaxFailed() {
                return null;
            }
        });
    }

    private void getSmsCodeCheck() {
        String phone = CompatHelper.getString(etAccount);
        if (!RegularUtil.isValidMobileNumber(phone)) {
            showBindToast("手机号格式错误");
        } else {
            showCaptchaDialog();
        }
    }

    private Gson mGson = new Gson();

    // 获取验证码
    private void getSmsCode() {

        mSmsCodeViewWrapper.startCountDown();

        Map<String, Object> params = new HashMap<>();
        params.put("mouldCode", "SMS_26775007");
        params.put("needCheck", 1);
        params.put("phone", CompatHelper.getString(etAccount));
        params.put("type", 1);

        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .sendSmsCode(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        showBindToast("验证码发送成功");
                    } else {
                        showBindToast(response.getErrorInfo());
                        mSmsCodeViewWrapper.stopCountDown();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                    mSmsCodeViewWrapper.stopCountDown();
                }));
    }
}